function ctr(tbody){
	var tr = new Element("TR");
	if (tbody)
		tbody.appendChild(tr)
	return tr
}
function ctd(tr){
	var td = new Element("TD");
	tr.appendChild(td)
	return td
}

function RuleMgnt(){}
RuleMgnt.RULESET_NAME = I18N.getText('js_rulemgnt_rule',"规则")
RuleMgnt.ruleType = null
RuleMgnt.rt = null
RuleMgnt.editPage = null
RuleMgnt.editPageSize = {y:300,x:460}
RuleMgnt.currentQt = null		//current
RuleMgnt.mgntQt	 = null			//mgnt	
RuleMgnt.lowerQt = null		//lower
RuleMgnt.currentView = null
RuleMgnt.mgntLower = false		//管理下级lower

RuleMgnt.getEditForm = function(){
	return $('ruleSetForm')
}
//创建所有的视图
RuleMgnt.createViews = function(divId,views,options){
	if (!RuleMgnt.ruleType){
		alert("必须设置ruleType")
		return
	}
	if (!views) views = 'current,mgnt,lower'	//缺省显示所有
	if (!options) options = {}
	var ruleType = RuleMgnt.ruleType
	DWR.call("ruleService.getRuleType",ruleType,function(rt){
	
		RuleMgnt.rt = rt
		Rpc.loadPage(divId,"/script/rule/rule_views_div.html");
		
		var vs = views.split(',')
		var tabs = new Array()
		var hasCurrent= false;
		var hasMgnt= false;
		var hasLower= false;
		
		var org = Common.cOrg();	//当前单位	
		for(var i=0;i<vs.length;i++)
		{
			if (vs[i]=='current'&&!hasCurrent)
			{
				hasCurrent = true
				tabs.push({name : "current",text : I18N.getText('js_rulemgnt_current_loyalty',"当前"+rt.name),tabFunc:RuleMgnt.showCurrent})
				var form = $('currentSearchForm')
				RuleMgnt.initSearchOrg(form)
				form.ruleType.value = ruleType
				var firstTd = $(form).getElement('td')
				if (rt.mainJudge && RuleMgnt.mainJudgeSearch){
					var td = new Element('td').inject(firstTd,'after')
					td.innerHTML = RuleMgnt.mainJudgeSearch
					
					if (RuleMgnt.mainJudgeSearchFunc){
						RuleMgnt.mainJudgeSearchFunc(form)
					}
				}
			}
			else if (vs[i]=='mgnt'&&!hasMgnt)
			{
				hasMgnt = true
				tabs.push({name : "mgnt",text:I18N.getText('js_rulemgnt_loyalty_management',rt.name+"管理"),tabFunc:RuleMgnt.showMgnt})
				
				var form = $('mgntSearchForm')
				RuleMgnt.initSearchOrg(form)
				RuleMgnt._initSearchForm(form,rt)
			}
			else if (vs[i]=='lower' && !hasLower)
			{
				hasLower = true
				tabs.push({name : "lower",text:I18N.getText('js_rulemgnt_search_lower_level',"下属机构"+RuleMgnt.RULESET_NAME+"查询"),tabFunc:RuleMgnt.showLower})
				
				RuleMgnt._initSearchForm($('lowerSearchForm'),rt)
			}
		}
		
		Eui.buildTabs("tabs_div",tabs);
		
		setPages(["currentView","mgntView","detailView","lowerView"]);	
		$('tabs_div').getElement('A').onclick();	//click first A
	})
	
	
}

RuleMgnt.selOrg = function(obj){
	var form = $(obj).getParent("form")
	SystemMgnt.selOrg(function(o){
		form.orgName.value = o.name
		if (form.orgId)
			form.orgId.value = o.id
		if (form.createOrg)
			form.createOrg.value = o.id
		if (form.orgLevel)
			form.orgLevel.value = o.orgLevel
	})
}
RuleMgnt.initSearchOrg = function(form){
	var org = Common.cOrg();
	form.orgId.value = org.id
	form.orgName.value = org.name
	if (RuleMgnt.mgntLower){
		form.orgLevel.value = org.orgLevel
		var a = form.getElement("a.orga")
		a.style.display = "";
	}
	
}
RuleMgnt._initSearchForm = function(form,rt){
	var thisYear = new Date().getFullYear()
	var years = new Array()
	for(var i=-5;i<5;i++)
		years.push({code:thisYear+i,text:thisYear+i})
			
	form.ruleType.value = rt.id
	Common.initDict(form.year,years);
	form.year.value = thisYear
	Common.initDict(form.status,RuleStatus.CATEGORY,I18N.getText('js_rulemgnt_all',"全 部"));
	var table = $(form).getElement('table')
	
	
	var newTr
	if (!rt.singleSet || rt.mainJudge && RuleMgnt.mainJudgeSearch){
		newTr = new Element('tr').inject(table.getElement('tr'),'after')	//插入新行
	}
	if (!rt.singleSet){
		var td = new Element('td').inject(newTr)
		td.innerHTML = "<label>"+I18N.getText('js_rulemgnt_campaign_name',RuleMgnt.RULESET_NAME+"名称")+"</label> <input type=text name=ruleName maxlength=20>"
		
	}
	if (rt.mainJudge && RuleMgnt.mainJudgeSearch){
		var td = new Element('td').inject(newTr)
		td.innerHTML = RuleMgnt.mainJudgeSearch
		
		
		if (RuleMgnt.mainJudgeSearchFunc){
			RuleMgnt.mainJudgeSearchFunc(form)
		}
	}
}
//查询列表取查询条件的方法
RuleMgnt._queryParamFunc = function(){
	var form
	if (RuleMgnt.currentView == 'mgnt')
		form =  $('mgntSearchForm')
	else if (RuleMgnt.currentView == 'lower')
	{
		form =  $('lowerSearchForm')
	}else if (RuleMgnt.currentView == 'current')
	{
		form =  $('currentSearchForm')
	}
	else
		alert('wrong view')
	var params = Common.getValues(form)
	if (params.year){
		var year = parseInt(params.year)
		params.beginDate = year+'-01-01'
		params.endDate = (year+1)+'-01-01'
	}
	params.ruleTitle = RuleMgnt.RULESET_NAME
	return params
}
RuleMgnt.showCurrent = function(){
	
	switchPage('currentView')
	RuleMgnt.currentView = 'current'
	
	if (!RuleMgnt.currentQt){
		var columns = []
		var rt = RuleMgnt.rt
		var displayC = new Array()
		for(var i=0;i<7;i++)
		{
			if (i==0&&rt.singleSet) continue
			if (i==4&&!rt.mainJudge) continue
			if (i==6&&!rt.hasSpecial) continue
			displayC.push(i)
		}
		var qt = new QueryTable("current_rule_list", "currentSearchForm", "currentList", columns, {
			failOrder : true,
			exportable:true,
			displayColumns:displayC,
			paramFunc:RuleMgnt._queryParamFunc
		});
		RuleMgnt.currentQt = qt
	}
	RuleMgnt.currentQt.showTable();
}

//操作
RuleMgnt.operFunc = function(v, r){
	var ruleSetId = r[0];
	var status = r[10];
	var endTime = r[5];
	var str = ""
	str += "<a href='#' onclick=\"RuleMgnt.view(" + ruleSetId + ",true);return false;\">"+I18N.getText('js_rulemgnt_view',"查看")+"</a>"
	var valid = endTime>new Date().format("yyyy-MM-dd");
	if (status===RuleStatus.DRAFT)
	{
		if (valid)
			str+=" <a href='#' onclick=\"RuleMgnt.submitForAudit(" + ruleSetId + ");return false;\">"+I18N.getText('js_rulemgnt_activate',"启用")+"</a>";	
		str+=" <a href='#' onclick=\"RuleMgnt.onEdit(" + ruleSetId + ");return false;\">"+I18N.getText('js_rulemgnt_edit',"编辑")+"</a>";
		str+=" <a href='#' onclick=\"RuleMgnt.onDelete(" + ruleSetId + ");return false;\">"+I18N.getText('js_rulemgnt_delete',"删除")+"</a>";
		
	}else if(valid && status===RuleStatus.NORMAL){
		str+=" <a href='#' onclick=\"RuleMgnt.onSuspend(" + ruleSetId + ");return false;\">"+I18N.getText('js_rulemgnt_suspend',"暂停")+"</a>";
		str+=" <a href='#' onclick=\"RuleMgnt.onStop(" + ruleSetId + ");return false;\">"+I18N.getText('js_rulemgnt_terminate',"停用")+"</a>";
		
	}else if(status===RuleStatus.REQUEST){
		str+=" <a href='#' onclick=\"RuleMgnt.cancelRequest(" + ruleSetId + ");return false;\">"+I18N.getText('js_rulemgnt_revoke_request',"撤销申请")+"</a>";
		
	}else if(status===RuleStatus.DECLNED ){
		str+=" <a href='#' onclick=\"RuleMgnt.declnedEdit(" + ruleSetId + ");return false;\">"+I18N.getText('js_rulemgnt_re_edit',"重新编辑")+"</a>";
		str+=" <a href='#' onclick=\"RuleMgnt.onDelete(" + ruleSetId + ");return false;\">"+I18N.getText('js_rulemgnt_delete',"删除")+"</a>";
		
	}else if(valid && status===RuleStatus.SUSPEND ){
		str+=" <a href='#' onclick=\"RuleMgnt.onResume(" + ruleSetId + ");return false;\">"+I18N.getText('js_rulemgnt_re_activate',"重新启用")+"</a>";
		
	}
	return str
}



RuleMgnt.auidtFunc = function(v,r){
	return  "<a href='#' onclick=\"RuleMgnt.showAuditHis(" + r[0] + ",true);return false;\">"+I18N.getText('js_rulemgnt_view',"查看")+"</a>"
}

RuleMgnt.showMgnt = function(norefresh){
	switchPage('mgntView')
	RuleMgnt.currentView = 'mgnt'
	
	if (!RuleMgnt.mgntQt){
		var columns = []
		columns[0] = {type:"checkbox"}
		columns[7] = {order:false}
		columns[8] = {order:false}
		columns[18] = {name:'oper',title:"操作",width:"15",render:RuleMgnt.operFunc,align:"left",order:false}
		columns[19] = {name:'auditingLog',title:"审核记录",width:"7",render:RuleMgnt.auidtFunc,align:"center",order:false}
	
		var rt = RuleMgnt.rt
			
		var displayC = new Array()
		for(var i=0;i<10;i++)
		{
			if (i==2&&rt.singleSet) continue
			if (i==6&&!rt.mainJudge) continue
			if (i==8&&!rt.hasSpecial) continue
			displayC.push(i)
		}
		
		displayC.push(18)
		displayC.push(19)
		var qt = new QueryTable("mgnt_rule_list", "mgntSearchForm", "mgntList", columns, {
			exportable:true,
			displayColumns:displayC,
			buttons:[
				{value:I18N.getText('js_rulemgnt_add',"增 加"),actions:RuleMgnt.onNew}
			],
			paramFunc:RuleMgnt._queryParamFunc
		});
		RuleMgnt.mgntQt = qt
	}
	if (!norefresh)
		RuleMgnt.mgntQt.showTable();
}

RuleMgnt.selectSubOrg = function(sorg){
	var form = $('lowerSearchForm')
	form.orgName.value = sorg.name;
	form.orgId.value = sorg.id;
}
			
RuleMgnt.lowerOperFunc = function(v, r){
	var str =  "<a href='#' onclick=\"RuleMgnt.view(" + r[0] + ");return false;\">"+I18N.getText('js_rulemgnt_view',"查看")+"</a>"
	return str
}

		
RuleMgnt.showLower = function(){
	switchPage('lowerView')
	RuleMgnt.currentView = 'lower'
	
	if (!RuleMgnt.lowerQt){
		var columns = []
		columns[0] = {type:"checkbox"}
		columns[18] = {name:'oper',title:"操作",width:"5",render:RuleMgnt.lowerOperFunc,align:"center",order:false}
		columns[19] = {name:'auditingLog',title:"审核记录",width:"5",render:RuleMgnt.auidtFunc,align:"center",order:false}
		
		var rt = RuleMgnt.rt
		var displayC = new Array()
		for(var i=0;i<9;i++)
		{
			if (i==2&&rt.singleSet) continue
			if (i==6&&!rt.mainJudge) continue
			if (i==8&&!rt.hasSpecial) continue
			displayC.push(i)
		}
		displayC.push(18)
		displayC.push(19)
		
		var qt = new QueryTable("lower_rule_list", "lowerSearchForm", "lowerList", columns, {
			exportable:true,
			displayColumns:displayC,
			paramFunc:RuleMgnt._queryParamFunc
		});
		RuleMgnt.lowerQt = qt
	}
	RuleMgnt.showLowerTable = function(){
		if (!checkForm('lowerSearchForm')) return;
		RuleMgnt.lowerQt.showTable();
	}
}

//提交审核
RuleMgnt.submitForAudit = function (ruleSetId){

	if(!(showQuestion(I18N.getText('js_rulemgnt_submit_activation_request',"确定提交启用申请吗?")))){
		return;
	}
	DWR.call("ruleMgntService.submitForAudit",ruleSetId,function(set){
		showInformation(I18N.getText('js_rulemgnt_activation_request_submitted',"启用申请提交成功!"));
		RuleMgnt.showMgnt()
	},{blockScreen:"true"});
}

RuleMgnt.auditHisFunc = function(v, r){
	var str =  "";
	
	if (r[9]==AuditStatus.OPEN && Common.cOrg().id==r.createOrgId)
		str+= "<a href='#' onclick=\"RuleMgnt.cancelAuditRequest('"+r.auditTypeUnqiueId+"'," + r.ruleSetId + ",true);return false;\">撤销</a>"
	if (!str)
		str += "<span style='color:gray'>"+I18N.getText('js_rulemgnt_no',"无")+"</span>"
	return str
}

RuleMgnt.cancelAuditRequest = function(uniqueId,ruleSetId){

	if(!(showQuestion(I18N.getText('js_rulemgnt_cancel_this_request',"确定撤销此申请吗?")))){
		return;
	}
	DWR.call("ruleMgntService.cancelRequest",uniqueId,ruleSetId,function(){
		showInformation(I18N.getText('js_rulemgnt_request_cancelled',"撤销申请成功!"));
		RuleMgnt.showAuditHis(ruleSetId);
		RuleMgnt.mgntRefresh = true
	},{blockScreen:"true"});
}

RuleMgnt.showAuditHis = function(ruleSetId){

	switchPage('detailView')
	$('detailDiv').empty()
	//onView里面没有返回btn
	var auditHisDiv = new Element('div',{id:'auditHisDiv'}).inject($('detailDiv'))
	
	var columns = []
	columns[15] = {title:"操作",width:"7",render:RuleMgnt.auditHisFunc,align:"left",order:false}
		
	var qt = new QueryTable("rule_audit_history", "", "auditHisDiv", columns, {});
	qt.paramFunc=function(){
		var params = {auditObjId:ruleSetId,auditCat:AuditCategory.RULE}
		return params
	}
	qt.showTable();
	
	//再插一个
	var backDiv = new Element('div').inject($('detailDiv'))
	RuleMgnt.mgntRefresh = false;
	backDiv.innerHTML = "<p><button type=button onclick=RuleMgnt.backShow(RuleMgnt.mgntRefresh)>"+I18N.getText('js_rulemgnt_return',"返 回")+"</button></p>"

}
RuleMgnt.view = function(ruleSetId){

	switchPage('detailView')
	RuleMgnt.onView("detailDiv",ruleSetId)
	
	var backDiv = new Element('div').inject($('detailDiv'))
	backDiv.innerHTML = "<p><button type=button onclick='RuleMgnt.backShow();'>"+I18N.getText('js_rulemgnt_return',"返 回")+"</button></p>"

}
//显示ruleSet
RuleMgnt.onView = function(showDivId,ruleSetId){
	
	Rpc.loadPage(showDivId,"/script/rule/ruleset_detail_div.html");
	
	$(showDivId).getElements('.ruleTitle').each(function(ele){
		ele.innerHTML = RuleMgnt.RULESET_NAME+ele.innerHTML
	})
	
	
		
	DWR.call("ruleMgntService.getRuleSet",ruleSetId,function(result){
		Common.showDetail(showDivId, result);
		var rt = result.rt
		var tr = $('mainJudgeTd').getParent()
	
		if (!rt.mainJudge)
			$('mainJudgeTd').dispose()
		if (rt.singleSet)
			$('ruleNameTd').dispose()
		if (tr.getChildren().length==1)
			new Element('td',{html:'&nbsp;'}).inject(tr)
		if (rt.mainJudge)
		{
			var mjt = result.mainJudgeText
			if (mjt.length<4){
				var pad = 4-mjt.length
				for (var i=0;i<pad;i++)
					mjt += "&nbsp;&nbsp;"
			}
			$('mainJudgeText').innerHTML = mjt
		}
		$('special_rule_div').style.display=rt.hasSpecial?"":"none"
		if (rt.hasSpecial){
			var html = "<table cellSpacing=0 cellPadding=2 width=100% border=0 class=ruleTable>"
			html += "<tr><th width=15%>"+I18N.getText('js_rulemgnt_execution_sequence',"执行顺序")+"</th><th>"+I18N.getText('js_rulemgnt_judging_condition',"判断条件")+"</th><th>"+I18N.getText('js_rulemgnt_execution_result',"执行结果")+"</th></tr>"
				
			if (result.ruleTexts){
				var ruleTexts 
				for(var j = 0; j<result.ruleTexts.length; j++){
					ruleTexts = result.ruleTexts[j]
					html += "<tr><td align=center>"
					html += (j+1)
					html += "</td><td>"
					html += ruleTexts.judge
					html += "</td><td>"
					html += ruleTexts.result
					html += "</td></tr>"
				}
				html += "<tr></tr>"
			}else{
				html += "<tr><td align=center colspan=3>"+I18N.getText('js_rulemgnt_no',"(无)")+"</td></tr>"
			}
			html += "</table>"
			$("ruleListDiv").innerHTML = html
			if (RuleMgnt.currentView=='mgnt'){
			
				var btnHtml = ""
				if (result.createOrg==Common.cOrg().id){
					btnHtml+= "<button type='button' onclick=RuleMgnt.onEdit("+ruleSetId+",true)>"+I18N.getText('js_rulemgnt_copy',"复 制")+"</button>&nbsp;"
					if (result.status==RuleStatus.DRAFT){
						btnHtml+= "<button type='button' onclick=RuleMgnt.submitForAudit("+ruleSetId+")>"+I18N.getText('js_rulemgnt_activate',"启 用")+"</button>&nbsp;"
						btnHtml+= "<button type='button' onclick=RuleMgnt.onDelete("+ruleSetId+")>"+I18N.getText('js_rulemgnt_delete',"删 除")+"</button>&nbsp;"
						btnHtml+= "<button type='button' onclick=RuleMgnt.onEdit("+ruleSetId+")>"+I18N.getText('js_rulemgnt_edit',"编 辑")+"</button>&nbsp;"
					}else if (result.status==RuleStatus.NORMAL){
						btnHtml+= "<button type='button' onclick=RuleMgnt.onSuspend("+ruleSetId+")>"+I18N.getText('js_rulemgnt_suspend',"暂 停")+"</button>&nbsp;"
						btnHtml+= "<button type='button' onclick=RuleMgnt.onStop("+ruleSetId+")>"+I18N.getText('js_rulemgnt_terminate',"停 用")+"</button>&nbsp;"
					}else if (result.status == RuleStatus.REQUEST){
						btnHtml+= "<button type='button' onclick=RuleMgnt.cancelRequest("+ruleSetId+")>"+I18N.getText('js_rulemgnt_revoke_request',"撤销申请")+"</button>&nbsp;"
					}else if (result.status == RuleStatus.DECLNED){
						btnHtml+= "<button type='button' onclick=RuleMgnt.onDelete("+ruleSetId+")>"+I18N.getText('js_rulemgnt_delete',"删 除")+"</button>&nbsp;"
						btnHtml+= "<button type='button' onclick=RuleMgnt.declnedEdit("+ruleSetId+")>"+I18N.getText('js_rulemgnt_re_edit',"重新编辑")+"</button>&nbsp;"
					}else if (result.status == RuleStatus.SUSPEND){
						btnHtml+= "<button type='button' onclick=RuleMgnt.onResume("+ruleSetId+")>"+I18N.getText('js_rulemgnt_re_activate',"重新启用")+"</button>&nbsp;"
					}
				}
				
				$("ruleSetBtnDiv").innerHTML = btnHtml
			}
		}
		
	});
}

//被拒绝的和撤销的规则，重新编辑
RuleMgnt.declnedEdit = function(ruleSetId){

	DWR.call("ruleMgntService.statusToDraft",ruleSetId,function(){
		RuleMgnt.showMgnt();
	},{blockScreen:true})
}

//撤销申请
RuleMgnt.cancelRequest = function(ruleSetId){

	if(!(showQuestion(I18N.getText('js_rulemgnt_sure_revoke_activation_request',"确定撤销启用申请吗?")))){
		return;
	}
	DWR.call("ruleMgntService.cancelRequest","create_rule",ruleSetId,function(){
		showInformation(I18N.getText('js_rulemgnt_sure_activation_request_revoked',"撤销启用申请成功!"));
		RuleMgnt.showMgnt();
	},{blockScreen:"true"});
}

RuleMgnt._showEditCtrls = function(){
	Rpc.loadPage("detailDiv","/script/rule/ruleset_edit_div.html");
	$("detailDiv").getElements('.ruleTitle').each(function(ele){
		ele.innerHTML = RuleMgnt.RULESET_NAME+ele.innerHTML
	})
	var rt = RuleMgnt.rt
	var form = $('ruleSetForm')
	if (rt.singleSet){
		var tr = form.getElement('tr')		//dispose name tr
		tr.dispose()
	}
	if (rt.mainJudge && RuleMgnt.mainJudgeEdit){
		var tr = form.getElement('tr')
		var newTr = new Element('tr').inject(tr,'before')
		var newTd = new Element('td').inject(newTr)
		newTd.innerHTML = RuleMgnt.mainJudgeEdit
		if (RuleMgnt.mainJudgeEditFunc)
			RuleMgnt.mainJudgeEditFunc(form)
	}
	
	if (RuleMgnt.mgntLower){
		var org = Common.cOrg();
		newTr = new Element('tr').inject(form.getElement('tr'),'after')	//插入新行
		var td = new Element('td').inject(newTr)
		var html = ""
		html += '<label>所属机构</label>  <input type=text name=orgName value="'+org.name+'" maxlength=20 readonly class=readonly>'
		html += '<input type="hidden" name="createOrg" value="'+org.id+'">'
		html += '<a class="orga" href="#" onclick="RuleMgnt.selOrg(this);">&nbsp;&nbsp;</a>'
		 
		td.innerHTML = html
	}
	
	if (RuleMgnt.defResultEdit){
		var p = form.getElement('tr').getParent()
		var newTr = new Element('tr').inject(p)
		var newTd = new Element('td').inject(newTr)
		newTd.innerHTML = RuleMgnt.defResultEdit
	}
	Eui.initDateInput("beginTimeDiv",I18N.getText('js_rulemgnt_effective_date',"生效日期"),"ruleSetForm","beginTime","date",true);
	Eui.initDateInput("endTimeDiv",I18N.getText('js_rulemgnt_expiry_date',"失效日期"),"ruleSetForm","endTime","futureDate",true);
}
//点击进入新增页面
RuleMgnt.onNew = function(){
	switchPage("detailView");
	RuleMgnt._showEditCtrls()
	
	var rt = RuleMgnt.rt

	$('special_rule_div').style.display=rt.hasSpecial?"":"none"
	if (rt.hasSpecial){
		
		var html = "<table cellSpacing=0 cellPadding=2 width=100% border=0 class=ruleTable>"
		html += "<tr><th width=18%>"+I18N.getText('js_rulemgnt_execution_sequence',"执行顺序")+"</th><th>"+I18N.getText('js_rulemgnt_judging_condition',"判断条件")+"</th><th>"+I18N.getText('js_rulemgnt_execution_result',"执行结果")+"</th><th width=25%>"
		html += "<button type='button' onclick=RuleMgnt.onEditRule()>"+I18N.getText('js_rulemgnt_new_condition',"新条件")+"</button>"
		html += "</th></tr>"
		html += "<tr></tr>"
		html += "</table>"
		$("ruleListDiv").innerHTML = html
	}
	
}

//那些参数名称是规则数值
RuleMgnt.valueNames = {
	amount:true,
	discountAmount:true,
	discountRate:true
}

//判断能否上移,判断返回结果的canUp,true为可以上移
RuleMgnt.checkMoveUp = function(tr,upTr){
	var rule = tr.ruleValue
	var upRule = upTr.ruleValue
	
	var parseParams = function(r){
		var res = {list:[],map:{}}
		for (p in r){
			if (p == "ruleText" || typeof r[p] == "function" || RuleMgnt.valueNames[p] || !r[p]) continue;
			res.list.push(p)
			res.map[p] = r[p]
		}
		return res
	}
	
	//p2 contains p1 is true
	var contains = function(ps,params){
		var b = true
		for (var j=0;j<ps.list.length;j++){
			var p = ps.list[j]
			if (!params.map[p] || params.map[p] != ps.map[p]){
				//参数名称不一致;参数名称一致,但是参数值不相等
				b = false;
				break; 
			}
		}
		return b
	}
	var res = {contain:false,canUp:true}
	if (upRule && rule){
		var params = parseParams(rule)
		var upParams = parseParams(upRule)
		if (upParams.list.length > params.list.length){
			//准备上移的规则,是上面规则的子集,则不能上移
			res.contain = contains(params,upParams)
			res.canUp = !res.contain
			return res;
		}else if (upParams.list.length == params.list.length){
			if (contains(upParams,params)) throw new Error(I18N.getText('js_rulemgnt_already_exists_Rule',"已存在相同类型的规则!")+"<br>"+upTr.ruleText)
		}else{
			//准备上移的规则,不是上面规则的子集,则可以上移
			res.contain = contains(upParams,params)
			res.canUp = true
			return res
		}
	}else
		res.canUp = false
	return res
}

RuleMgnt.insertRule = function(v2,ruleText){
	var tbody = $("ruleListDiv").childNodes[0].childNodes[0]
	var tr = ctr();
	tr.ruleText = ruleText.judge + " " + ruleText.result
	tr.ruleValue = v2
	var td = ctd(tr);
	td.align = "center"
	td.innerHTML = tbody.childNodes.length-1
	
	td = ctd(tr);
	td.innerHTML =ruleText.judge

	td = ctd(tr);
	td.innerHTML =ruleText.result
	
	td = ctd(tr);
	td.innerHTML = "<a href=# name='delete' onclick=RuleMgnt.deleteRule(this)>"+I18N.getText('js_rulemgnt_delete',"删除")+"</a>&nbsp;<a href=# name='moveup' onclick=RuleMgnt.ruleUp(this)>"+I18N.getText('js_rulemgnt_up',"上移")+"</a>&nbsp;<a href=# name='movedown' onclick=RuleMgnt.ruleDown(this)>"+I18N.getText('js_rulemgnt_down',"下移")+"</a>&nbsp;"

	try{
		var insertTr;
		var res;
		//新规则为最后一条,然后逐行上移,直至不能移动为止;
		//如果上移过程中发现包含规则,则记录插入位置为该规则的上面,在扫描结束后插入规则
		
		for (var i = tbody.childNodes.length-1 -1;i>0;i--){
			var upTr = tbody.childNodes[i]
			res = RuleMgnt.checkMoveUp(tr,upTr)
			if (!res.canUp){
				insertTr = upTr
				break;
			}else if (res.contain)
				//如果可以上移,并且新的规则包含该规则,则记录插入位置为该规则前面
				insertTr = upTr
		}
		
		//res.canUp == true的情况是:所有的行都扫描过后,发现新规则可以增加至任意位置
		var ele = insertTr?(res.canUp?insertTr:insertTr.nextSibling):tbody.childNodes[tbody.childNodes.length-1]
		Element.Inserters.before(tr,ele)
	}catch(e){showError(e.description);return;}
	
}

RuleMgnt.onEditRule = function(){
	var form = $('ruleSetForm')
	var url = this.editPage
	if (this.rt.mainJudge){
		if (form&& form.mainJudge&&form.mainJudge.value)
			url = spellUrl(url,{mainJudge:form.mainJudge.value})
		else
		{
			showInformation("必须先选择"+this.rt.mainJudge.name)
			return
		}
	}
	var size= this.editPageSize
	openDialogFrame(url,I18N.getText('js_rulemgnt_edit_special_rule',"编辑特殊规则"),size.y,size.x,function(v){
		var v2 = {}
		for (p in v){
			if(typeof v[p] == "function") continue;
			v2[p] = v[p]
		}
		DWR.call("ruleMgntService.getRuleTextByParams",RuleMgnt.ruleType,v2,function(ruleText){
			RuleMgnt.insertRule(v2,ruleText)
			RuleMgnt.refreshRuleIndex();
		});
	})
}


RuleMgnt.deleteRule = function(ruleA){
	var ruleTr = ruleA.parentNode.parentNode
	ruleTr.parentNode.removeChild(ruleTr)
	this.refreshRuleIndex()
}

RuleMgnt.ruleUp = function(ruleA){
	if (ruleA.disabled) return;
	var ruleTr = ruleA.parentNode.parentNode
	var ind = parseInt(ruleTr.childNodes[0].innerHTML)
	var tbody = ruleTr.parentNode
	if (ind>1){
	
		//判断是否可以上移
		var canUp = RuleMgnt.checkMoveUp(ruleTr,ruleTr.previousSibling).canUp
		if (!canUp){
			showError("规则:"+ruleTr.ruleText + " <br>不能在规则:"+ ruleTr.previousSibling.ruleText +"之前");
			return;
		}
		tbody.removeChild(ruleTr)
		tbody.insertBefore(ruleTr,tbody.childNodes[ind-1])
		this.refreshRuleIndex()
		
	}
}

RuleMgnt.ruleDown = function(ruleA){
	if (ruleA.disabled) return;
	var ruleTr = ruleA.parentNode.parentNode
	var ind = parseInt(ruleTr.childNodes[0].innerHTML)
	var tbody = ruleTr.parentNode

	if (ind<tbody.childNodes.length-1-1){
		
		//判断是否可以下移
		var canDown = RuleMgnt.checkMoveUp(ruleTr.nextSibling,ruleTr).canUp
		if (!canDown){
			showError("规则:"+ruleTr.ruleText + " <br>不能在规则:"+ ruleTr.nextSibling.ruleText +"之后");
			return;
		}
		tbody.removeChild(ruleTr)
		tbody.insertBefore(ruleTr,tbody.childNodes[ind+1])
		this.refreshRuleIndex()
		
	}
}

RuleMgnt.refreshRuleIndex = function(){
	var tbody = $("ruleListDiv").childNodes[0].childNodes[0]
	for(var i=1;i<tbody.childNodes.length-1;i++){
		var tr = tbody.childNodes[i]
		tr.childNodes[0].innerHTML = i
		
		//更新链接状态
		var canUp = RuleMgnt.checkMoveUp(tr,tr.previousSibling).canUp
		var canDown = RuleMgnt.checkMoveUp(tr.nextSibling,tr).canUp
		var links = tr.getElements("A")
		for (var j=0;j<links.length;j++){
			var a = links[j]
			if (a.name == "moveup"){
				//第一条和上条规则包含当前规则的,不能上移
				if (!canUp)
					a.disabled = true
				else 
					a.disabled = false
			}else if (a.name == "movedown"){
				//最后一条和当前规则包含下条规则的,不能下移
				if (!canDown)
					a.disabled = true
				else
					a.disabled = false;
			}
		}
	}
}

//保存和修改方法
RuleMgnt.onSave = function(){
	var form = $("ruleSetForm");
	if(!checkForm(form))return;
	var rt = RuleMgnt.rt
	if (rt.mainJudge){
		if (form.mainJudge&&!form.mainJudge.value)
		{
			//合同类别
			showInformation("需要设置"+rt.mainJudge.text)
			return 
		}
	}
	if(!(showQuestion(I18N.getText('js_rulemgnt_save',"您确认保存吗?")))) return
	var defResult = null
	if (RuleMgnt.beforeSave){
		defResult = RuleMgnt.beforeSave()
		if (defResult==-1) return
	}
	
	var formValue = Common.getValues(form);
	formValue.ruleType = RuleMgnt.ruleType
	
	var trs = $("ruleListDiv").getElements('tr')
	var rules = new Array()
	for(var i=1;i<trs.length-1;i++){
		if (trs[i].ruleValue)
			rules.push(trs[i].ruleValue)
	}
	DWR.call("ruleMgntService.saveRuleSet",formValue,rules,defResult,function(set){
		showInformation(I18N.getText('js_rulemgnt_saved',"保存成功!"));
		RuleMgnt.showMgnt()
	},{blockScreen:"true"});
}


//进入修改明细
RuleMgnt.onEdit = function(ruleSetId,copy){
 
	switchPage("detailView")
	
	RuleMgnt._showEditCtrls()
	
	DWR.call("ruleMgntService.editRuleSet",ruleSetId,function(result){
		if (copy){
			result.id= null
			result.beginTime = null;
			result.endTime = null;
			result.name = null;
		}
		Common.setValues("ruleSetForm", result);
		if (RuleMgnt.beforeEdit){
			RuleMgnt.beforeEdit(result)
		}
		
		var rt = RuleMgnt.rt
		$('special_rule_div').style.display=rt.hasSpecial?"":"none"
		if (rt.hasSpecial){
		
			var html = "<table cellSpacing=0 cellPadding=2 width=100% border=0 class=ruleTable>"
				html += "<tr><th width=15%>"+I18N.getText('js_rulemgnt_execution_sequence',"执行顺序")+"</th><th>"+I18N.getText('js_rulemgnt_judging_condition',"判断条件")+"</th><th>"+I18N.getText('js_rulemgnt_execution_result',"执行结果")+"</th><th width=25%>"
				html += "<button type='button' onclick=RuleMgnt.onEditRule()>"+I18N.getText('js_rulemgnt_new_condition',"新条件")+"</button>"
				html += "</th></tr>"
				html += "</table>"
				$("ruleListDiv").innerHTML = html
				
			var tbody = $("ruleListDiv").childNodes[0].childNodes[0]
			if (result.ruleTexts){
				
				var ruleTexts 
				for(var j = 0; j<result.ruleTexts.length; j++){
					ruleTexts = result.ruleTexts[j]
					var tr = ctr(tbody)
					var ruleText = result.rules[j]
					tr.ruleText = ruleTexts.judge + " " + ruleTexts.result
					tr.ruleValue = ruleText
					var td = ctd(tr)
					td.align="center"
					td.innerHTML = j+1
					
					td = ctd(tr)
					td.innerHTML = ruleTexts.judge
					
					td = ctd(tr)
					td.innerHTML = ruleTexts.result
					
					td = ctd(tr)
					td.innerHTML = "<a href=# name='delete' onclick=RuleMgnt.deleteRule(this)>"+I18N.getText('js_rulemgnt_delete',"删除")+"</a>&nbsp;<a href=# name='moveup' onclick=RuleMgnt.ruleUp(this)>"+I18N.getText('js_rulemgnt_up',"上移")+"</a>&nbsp;<a href=# name='movedown' onclick=RuleMgnt.ruleDown(this)>"+I18N.getText('js_rulemgnt_down',"下移")+"</a>&nbsp;"
				}
			}
			
			ctr(tbody)
			RuleMgnt.refreshRuleIndex()
		}
	});
	
}
//删除方法
RuleMgnt.onDelete = function(ruleSetId){
	
	if(!(showQuestion(I18N.getText('js_rulemgnt_sure_delete',"确定删除吗?")))){
		return;
	}
		
	DWR.call("ruleMgntService.deleteRuleSet",ruleSetId,function(){
		showInformation(I18N.getText('js_rulemgnt_deleted',"删除成功!"));
		RuleMgnt.showMgnt()
	},{blockScreen:"true"});
}

//撤销方法
RuleMgnt.onStop = function(ruleSetId){
	
	if(!(showQuestion(RuleMgnt.RULESET_NAME+I18N.getText('js_rulemgnt_restarted_termination',"停用后不能被重新启动！\n 确定申请停用此")+RuleMgnt.RULESET_NAME+I18N.getText('js_rulemgnt_MA',"吗?")))){
		return;
	}
	DWR.call("ruleMgntService.cancelRuleSet",ruleSetId,function(){
		showInformation(I18N.getText('js_rulemgnt_submitted',"停用申请提交成功!"));
	},{blockScreen:"true"});
}

//暂停方法
RuleMgnt.onSuspend = function(ruleSetId){
	if(!(showQuestion(I18N.getText('js_rulemgnt_confirm_request_suspend',"确定申请暂停此")+RuleMgnt.RULESET_NAME+I18N.getText('js_rulemgnt_MA',"吗?")))){
		return;
	}
	DWR.call("ruleMgntService.suspendRuleSet",ruleSetId,function(){
		showInformation(I18N.getText('js_rulemgnt_suspension_request_submitted',"暂停申请提交成功!"));
	},{blockScreen:"true"});
}

//重启方法
RuleMgnt.onResume = function(ruleSetId){
	
	if(!(showQuestion(I18N.getText('js_rulemgnt_confirm_request_restart',"确定申请重启此")+RuleMgnt.RULESET_NAME+I18N.getText('js_rulemgnt_MA',"吗?")))){
		return;
	}
	DWR.call("ruleMgntService.resumeRuleSet",ruleSetId,function(){
		showInformation(I18N.getText('js_rulemgnt_Restart_request_submitted',"确定申请重启此"));
	},{blockScreen:"true"});
}
//修改保存后返回
RuleMgnt.backShow = function (){
	if (RuleMgnt.currentView=='lower')
		RuleMgnt.showLower()
	else{
		RuleMgnt.showMgnt(true)
	}
}

//以下是审核管理的内容
function AuditMgnt(){}
AuditMgnt.currentRequestId	
AuditMgnt.refreshFunc = null	
AuditMgnt.showDetail = function(divId,requestId,edit){
			
	Rpc.loadPage(divId,"/script/rule/audit_detail_div.html");
			
	this.currentRequestId = requestId
			
	$('comment').value=''
	$('auditProperties').style.display = edit?"none":""
	$('commentDiv').style.display = edit?"":"none"
	$("approvebtn").style.display = edit?"":"none"
	$("refusebtn").style.display = edit?"":"none"

	DWR.call("auditService.getAuditProperties",requestId,function(result){
		if (result.auditTime)
			result.auditTime = result.auditTime.format("yyyy-MM-dd hh:mm:ss")
		if (result.recordTime)
			result.recordTime = result.recordTime.format("yyyy-MM-dd hh:mm:ss")
		Common.showDetail('reqProperties',result)
		Common.showDetail('auditProperties',result)
	});

}

AuditMgnt.approveRequest = function(){
	if (!this.currentRequestId)
	{
		showInformation(I18N.getText('js_rulemgnt_no_audit_request',"没有选择待审核的申请"))
		return
	}
	var comment = $('comment')
	if (comment.value){
		if (comment.value.length>100)
		{
			showInformation(I18N.getText('js_rulemgnt_comment_characters',"反馈意见应该在100字以内"))
			return;
		}
	}
	
	if (!showQuestion(I18N.getText('js_rulemgnt_approve_request',"是否批准该申请？"))) return;

	DWR.call("auditService.approveRequest",this.currentRequestId,comment.value,function(){
		showInformation(I18N.getText('js_rulemgnt_approved_request',"该申请被批准"));
		AuditMgnt.refreshFunc();
	})
}

AuditMgnt.refuseRequest = function(){
	if (!this.currentRequestId)
	{
		showInformation(I18N.getText('js_rulemgnt_no_audit_request',"没有选择待审核的申请"))
		return
	}
	var comment = $('comment')
	if (comment.value){
		if (comment.value.length>100)
		{
			showInformation(I18N.getText('js_rulemgnt_comment_characters',"反馈意见应该在100字以内"))
			return;
		}
	}
	
	if (!showQuestion(I18N.getText('js_rulemgnt_reject_request',"是否拒绝该申请？"))) return;
	
	DWR.call("auditService.refuseRequest",this.currentRequestId,comment.value,function(){
		showInformation(I18N.getText('js_rulemgnt_rejected_request',"该申请被拒绝"));
		AuditMgnt.refresh();
	})
}

AuditMgnt.refresh = function(){
	if (this.refreshFunc) this.refreshFunc()
}

AuditMgnt.back = function(){
	if (this.backFunc) this.backFunc()
	else
		this.refresh()
}

//audit
function RuleAudit(){}
RuleAudit.qt = null;	//数据表格对象
		
RuleAudit.loadRuleAuditTypes = function(){

	var items = DWR.syncCall("auditService.findAuditTypesByCategory",AuditCategory.RULE)
	var item;
	for(var i=0;i<items.length;i++) {
		item = items[i];
		item.code =	item.id				// for select usage
		item.text = item.name
	}
	return items
}
		
RuleAudit.createView = function(divId){		
	Common.registerSpecialDict("rule_audit_type",this.loadRuleAuditTypes)
	
	Rpc.loadPage(divId,"/script/rule/rule_audit_div.html");
	setPages(["listview","detview"]);
	var searchForm = $('searchForm')

	searchForm.orgId.value = Common.cOrg().id;
	Common.initDict(searchForm.auditType,"rule_audit_type" , I18N.getText('js_rulemgnt_all',"全部"));
	Common.initDict(searchForm.status,AuditStatus.CATEGORY , I18N.getText('js_rulemgnt_all',"全部"));			//初始化性别(查询form)
	this.createTable();
	
	
	AuditMgnt.refreshFunc = function(){
		switchPage("listview");
		RuleAudit.qt.showTable();
	}
	
	
	AuditMgnt.backFunc = function(){
		switchPage("listview");
	}
}
		
		
RuleAudit.createTable = function(){
	var columns = []
	columns[6] = {defOrder:"desc"}
	columns[18] = {name:"oper", title:"操作",width:"15",render:function(v,r){
		var str = "";
		if (r[9] == AuditStatus.OPEN){
			str = "<a href='#' onclick='RuleAudit.showView("+r[10]+","+r[11]+",\""+r[12]+"\",true)'>"+I18N.getText('js_rulemgnt_audit',"审核")+"</a>"
		}else
			str = "<a href='#' onclick='RuleAudit.showView("+r[10]+","+r[11]+",\""+r[12]+"\")'>"+I18N.getText('js_rulemgnt_view',"查看")+"</a>"
		return str;
	},align:"center",order:false}
	var searchForm = $('searchForm')
	this.qt = new QueryTable("audit_rule_list", null, "datalist", columns,{
		paramFunc : function(){
			var cOrg = Common.cOrg()
			var params = Common.getValues(searchForm)
			params.ruleTypes = RuleAudit.ruleTypes
			params.orgLevel = cOrg.orgLevel;
			params.orgId = cOrg.id;
			params.title = searchForm.auditType.options[searchForm.auditType.selectedIndex].text;
			params.auditReq = RuleAudit.auditReq;
			return params
		}
	});
	this.qt.showTable();
}
		
RuleAudit.showView = function(requestId,ruleSetId,auditType,edit){
			
	switchPage("detview");
	AuditMgnt.showDetail('auditDetailDiv',requestId,edit)
	
	this.setConflictDiv(ruleSetId,auditType,edit)
	RuleMgnt.onView("ruleview",ruleSetId)
}
		
//设置规则冲突的内容
RuleAudit.setConflictDiv = function(ruleSetId,auditType,edit){

	var conflictDiv = $('conflictDiv')
	conflictDiv.style.display = "none"
	if (!edit) return
	if (auditType!=AuditType.CREATE_RULE&&auditType!=AuditType.RESUME_RULE) return
	DWR.call("ruleMgntService.findConflictRules",ruleSetId,function(results){
		if (!results || results.length==0)
		{
			//没有冲突
			return
		}
		conflictDiv.style.display = ""
		var listDiv = conflictDiv.getElement('.conflictList')
		
		var html = ""
		var cr
		html += "<table>"
		html += "<tr><td width=22%>开始日期</td><td width=22%>结束日期</td><td width=20%>缺省结果</td><td>特殊规则</td></tr>"
		for(var i=0;i<results.length;i++){
			cr = results[i]
			html += "<tr>"
			html += "<td>" + cr.beginTime.format("yyyy-MM-dd") + "</td>"
			html += "<td>" + cr.endTime.format("yyyy-MM-dd") + "</td>"
			html += "<td>" + (cr.defResult?cr.defResult:'(无)') + "</td>"
			html += "<td>" + (cr.rules?cr.rules:'(无)') + "</td>"
			html += "</tr>"
		}
		html += "</table>"
		
		listDiv.set('html',html)
		 
	})
}
		
